(function (window) {
  //符合commonjs规范引入依赖
  if (typeof module !== 'undefined') {
    window.saveAs = require('file-saver');
    window.baidu = undefined;
  }
  // html标签的xmls必须设置否则默认打开的是web版式
  function getModelHtml(mhtml, style = '') {
    return `
      <!DOCTYPE>
      <html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\">
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->
      <style>
        ${style}
      </style>
      </head>
      <body>
        ${mhtml}
      </body>
      </html>
    `;
  }

  //主函数
  let exportWord = ({ mhtml, style, filename, data, selector }) => {
    if (selector) {
      let nodes = window.document.querySelectorAll(selector);
      mhtml = nodes.length > 0 ? Array.from(nodes).reduce((a, b) => a + b.innerHTML, '') : '';
    }

    //没有baiduTemplatePro.js依赖时必须传入selector
    if (!selector && typeof baidu === 'undefined') {
      console.error('wordExport : missing (selector) for params without depandency (baiduTemplatePro.js)');
      return;
    }
    if (typeof saveAs === 'undefined') {
      console.error('wordExport : missing dependency (FileSaver.js)');
      return;
    }

    //没有模板引擎时，将获取节点的html字符串生成模板
    let html =
      typeof baidu !== 'undefined' ? baidu.template(getModelHtml(mhtml, style), data) : getModelHtml(mhtml, style).replaceAll('break-before: page;', 'page-break-before:always;');

    let blob = new Blob([html], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' });
    console.log(html, blob);
    saveAs(blob, filename + '.docx');
  };
  //添加exportWord到全局对象
  window.exportWord = window.exportWord || exportWord;

  //如果符合commonjs规范，exports出去
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = { exportWord };
  }
})(window);
